package com.zeroup.auto.socket;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.blankj.utilcode.util.DeviceUtils;
import com.zeroup.auto.app.ZeroneAppliction;
import com.zeroup.auto.assists.next.LoginVo;
import com.zeroup.auto.assists.next.NextStepBean;
import com.zeroup.auto.socket.bean.WsMsg;
import com.zeroup.auto.utils.Base64Util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketJb {

    private static String  wsUrl = "ws://"+ ZeroneAppliction.HOST+"/prod-api/sysMsg/";

    private Handler manHandler = null;

    public WebSocketJb(Handler manHandler) {
        this.manHandler = manHandler;
    }

    private int reconnectInterval = 3000; // 重连间隔3秒

    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable heartbeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (webSocket != null && webSocket.send("heartbeat")) {
                // 成功发送心跳，可以设置下一个心跳
                handler.postDelayed(this, 10000); // 每30秒发送一次心跳
            } else {
                // WebSocket连接已关闭或不可用，取消后续心跳
                handler.removeCallbacks(this);
            }
        }
    };

    private WebSocket webSocket;
    private OkHttpClient client = new OkHttpClient();

    public boolean isClient = false;

    public void startWebSocket(String userID,String sbh) {
        LoginVo vo = new LoginVo();
        vo.setUn(userID);
        vo.setSbh(sbh);
        vo.setSbCode(DeviceUtils.getAndroidID());
        String json = JSON.toJSONString(vo);
        String token = new String(Base64Util.encode(json.getBytes()));
        Request request = new Request.Builder()
                .url(wsUrl+token)
                .build();

        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                // 连接成功
                Log.d("websocket:===>","链接成功");
                // 连接打开时开始发送心跳
                handler.post(heartbeatRunnable);
                isClient = true;
                Message m = new Message();
                m.what = 99;
                m.obj = "服务器连接成功";
                manHandler.sendMessage(m);
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                // 接收到文本消息
                Log.d("websocket:===>",text);
                JSONObject wsMsg = JSON.parseObject(text);
                if(wsMsg.getIntValue("ac")==1){
                    Log.d("websocket:====>","执行自动命令");
                    WsMsg<NextStepBean> wsMsg1 = JSON.parseObject(text, new TypeReference<WsMsg<NextStepBean>>() {});
                    Message m = new Message();
                    m.what = 1;
                    m.obj = wsMsg1.getData();
                   manHandler.sendMessage(m);
                }else if(wsMsg.getIntValue("ac")==-2){
                    Log.d("websocket:====>","停止命令");
                    Message m = new Message();
                    m.what = -2;
                    manHandler.sendMessage(m);
                }else if(wsMsg.getIntValue("ac")==97){
                    Log.d("websocket:====>","app更新");
                    Message m = new Message();
                    m.what = 97;
                    m.obj = wsMsg.getString("data");
                    manHandler.sendMessage(m);
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                // 接收到二进制消息
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                // 连接即将关闭
                Log.d("websocket:===>","连接即将关闭");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
                // 连接失败
                Log.d("websocket:===>","连接失败");
                isClient = false;

                Message m2 = new Message();
                m2.what = 100;
                m2.obj = "服务器连接失败";
                manHandler.sendMessage(m2);
                try {
                    Thread.sleep(reconnectInterval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startWebSocket(userID,sbh);// 重连
                Message m3 = new Message();
                m3.what = 98;
                m3.obj = "尝试重新连接....";
                manHandler.sendMessage(m3);
            }
        });
    }

    public void sendMessage(String message) {
        if (webSocket != null) {
            webSocket.send(message);
        }
    }

    public void closeWebSocket() {
        if (webSocket != null) {
            webSocket.close(1000, "Goodbye");
        }
    }

    public boolean isClose(){
        return this.isClient;
    }
}